package com.auto.learning.tools;

import java.util.List;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;

import android.content.Context;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

/**
 * Cookies的工具类
 *@ClassName:  CookiesUtil
 *All rights Reserved, Designed By isoftStone 
 *Copyright:    Copyright(C) 2013 
 *Company:      isoftStone Holdings Limited 
 *@author:     Wen Weiquan
 *@version:    V1.0
 *@date 2013-11-27 下午6:18:54
 */
public class CookiesUtil {
	private static String TAG=CookiesUtil.class.getSimpleName();
	
	private static CookieStore cookieStore=null;
	private static Object lockObject=new Object();
	
	/**
	 * 获取共享的CookieStore的一个复制本
	 * @return
	 */
	public static CookieStore getCookieStoreCopy(){
		CookieStore newCookieStore=new BasicCookieStore();
		
		if(null!=cookieStore){
			List<Cookie> cookiesList=cookieStore.getCookies();

			for(int i=0; i<cookiesList.size();i++){
				newCookieStore.addCookie(cookiesList.get(i));
			}
					
		}
		
		return newCookieStore;
	}
	
	/**
	 * 保存CookieStore
	 * @param newCookieStore
	 */
	public static void saveCookieStore(CookieStore newCookieStore){
		synchronized (lockObject) {
			cookieStore=newCookieStore;
		}

	}

	/**
	 * 设置WebView的Cookies
	 * @param context
	 */
	public static void setWebViewCookies(Context context) {
		// TODO Auto-generated method stub
		CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
		cookieSyncManager.sync();
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
//		cookieManager.removeSessionCookie();

		
		org.apache.http.client.CookieStore cookieStore=CookiesUtil.getCookieStoreCopy();
		
		List<Cookie> cookiesList=cookieStore.getCookies();
		String domainName="";
		for(int i=0;i<cookiesList.size();i++){
			Cookie cookie=cookiesList.get(i);
			String cookieString = cookie.getName() + "=" + cookie.getValue() + "; path=/";// +cookie.getDomain();
			domainName=cookie.getDomain();
			cookieManager.setCookie(cookie.getDomain(), cookieString);
			domainName="https://"+domainName;
			cookieManager.setCookie(domainName, cookieString);
		}
		
//		cookieManager.setCookie("172.22.13.26", "jsession=xxxxxxxx;");
		
		
		Log.d("HttpCookies", "WebKit Cookies domain:"+domainName);
//		String cookieString=cookieManager.getCookie("172.22.13.26");
		String cookieString=cookieManager.getCookie(domainName);
		Log.d("HttpCookies", "WebKit Cookies:"+cookieString);
		
		CookieSyncManager.getInstance().sync();
	}
}
